package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.admin.http.history;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import luj.tool.jnproxyan.proxy.admin.AdminHttpHandler;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.stats.http.history.state.HttpHistoryItem;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;

@Component
final class OnHttpHistory implements Socks5Actor.Handler<HttpHistoryMsg> {

  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    HttpHistoryMsg msg = ctx.getMessage(this);

    List<?> itemList = self.getHttpHistoryDat().getItemList().stream()
        .sorted(comparing(HttpHistoryItem::getItemId, reverseOrder()))
        .map(this::makeRow)
        .collect(Collectors.toList());

    Map<String, ?> data = ImmutableMap.of(
        "history", makeHistoryTable(itemList)
    );

    AdminHttpHandler.Context http = msg.http();
    http.responsePage(ImmutableMap.of(
        "data", http.encodeJson(data)
    ));
  }

  private Map<String, ?> makeHistoryTable(List<?> itemList) {
    return ImmutableMap.of(
        "header", ImmutableList.of("#", "地址", "路径", "发送", "接收", "响应码"),
        "body", itemList
    );
  }

  private Map<String, ?> makeRow(HttpHistoryItem item) {
    return ImmutableMap.of(
//        "req", item.requestId().toString(),
        "data", renderItem(item)
    );
  }

  private List<?> renderItem(HttpHistoryItem item) {
    String addr = item.getHost() + ":" + item.getPort();
    List<Object> result = new LinkedList<>(ImmutableList.of(item.getItemId(), addr));

    result.add(getUri(item));
    result.add(getBytesP2s(item));
    result.add(item.getBytesServer2p());

    return result;
  }

  private String getUri(HttpHistoryItem item) {
    String uri = item.getUri();
    if (uri == null) {
      if (item.getBytesProxy2s() > 0) {
        return "<SSL>";
      }
      return "<未连上>";
    }

    int maxLen = 75;
    if (uri.length() <= maxLen) {
      return uri;
    }
    return uri.substring(0, maxLen - 1) + "...";
  }

  private Object getBytesP2s(HttpHistoryItem item) {
    int bytes = item.getBytesProxy2s();
    if (bytes <= 0) {
      return "-";
    }
    return bytes;
  }
}
